package guava;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.HashMap;

/**
 * Immutable Collections：不可变集合
 * User: Realfighter
 * Date: 2014/10/19
 * Time: 21:56
 */
public class ImmutableCollectionsTest {

    @Test
    public void testImmutableCollections() {

        //builder模式创建不可变Set集合
        ImmutableSet<String> immutableSetByBuilder = ImmutableSet
                .<String>builder().add("First")
                .addAll(Lists.asList("Second", new String[]{"Third"}))
                .build();
        //of方法创建不可变Set集合
        ImmutableSet<String> immutableSetByOf = ImmutableSet
                .<String>of("First", "Second", "Third");
        //copyOf方法创建不可变Set集合
        ImmutableSet<String> immutableSetByCopyOf = ImmutableSet
                .<String>copyOf(new String[]{"First", "Second", "Third"});

        //builder模式创建不可变List集合
        ImmutableList<String> immutableListByBuilder = ImmutableList
                .<String>builder().add("First")
                .addAll(Lists.asList("Second", new String[]{"Third"}))
                .build();
        //of方法创建不可变List集合
        ImmutableList<String> immutableListByOf = ImmutableList
                .<String>of("First", "Second", "Third");
        //copyOf方法创建不可变List集合
        ImmutableList<String> immutableListByCopyOf = ImmutableList
                .<String>copyOf(new String[]{"First", "Second", "Third"});

        //builder模式创建不可变Map集合
        ImmutableMap<String, String> immutableMapByBuilder = ImmutableMap
                .<String, String>builder().put("First", "1")
                .putAll(new HashMap<String, String>() {
                    {
                        put("Second", "2");
                        put("Third", "3");
                    }
                }).build();
        //of方法创建不可变Map集合
        ImmutableMap<String, String> immutableMapByOf = ImmutableMap
                .<String, String>of("First", "1", "Second", "2", "Third", "3");
        //copyOf方法创建不可变Map集合
        ImmutableMap<String, String> immutableMapByCopyOf = ImmutableMap
                .<String, String>copyOf(new HashMap<String, String>() {
                    {
                        put("First", "1");
                        put("Second", "2");
                        put("Third", "3");
                    }
                });
    }
}
